import sys

import pygame
import tools.ini as ini
import queue
import threading

stop_event = threading.Event()

q = queue.Queue()
temp_o = {}
event_list = {}
lock = threading.Lock()

class PyHelp:

    def main_loop(self):
        global stop_event
        global PyScreen
        global event_list
        global q
        # 初始化pygame
        pygame.init()
        # 设置窗口
        PyScreen = pygame.display.set_mode((self.ini["w"], self.ini["h"]))
        pygame.display.set_caption(self.ini["title"])

        PyScreen.fill((self.ini["color"]["r"], self.ini["color"]["g"], self.ini["color"]["b"]))
        while True:
            # 事件接受
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    print("Event Click")
                    if self.screen_id not in event_list:
                        event_list[self.screen_id] = []
                    # 鼠标点击事件
                    mouse_pos = pygame.mouse.get_pos()  # 获取鼠标点击位置
                    q.put({"type": "screen", "operation": "mouse_click", "data": {"mouse_pos": mouse_pos}})

            while not q.empty():
                item = q.get()
                """# 调用多线程执行operation函数并传递item
                threading.Thread(target=self.operation, args=(item,)).start()
                q.task_done()  # 任务完成"""

                self.operation(item)
                # 更新显示
                pygame.display.flip()

                # 设置帧率
                pygame.time.Clock().tick(self.ini["fps"])
            pygame.display.flip()

    def __init__(self):
        global stop_event
        print("""
            ____                                   __  __     __               
   / __ \__  ______ _____ _____ ___  ___  / / / /__  / /___  ___  _____
  / /_/ / / / / __ `/ __ `/ __ `__ \/ _ \/ /_/ / _ \/ / __ \/ _ \/ ___/
 / ____/ /_/ / /_/ / /_/ / / / / / /  __/ __  /  __/ / /_/ /  __/ /    
/_/    \__, /\__, /\__,_/_/ /_/ /_/\___/_/ /_/\___/_/ .___/\___/_/     
      /____//____/                                 /_/                 
        """)
        print("ObJect is being created...")
        # 导入ini文件
        self.screen = ini.data("screen")
        self.ini = ini.data("ini")

        # 设置初始屏幕为"1"
        self.screen_id = list(self.screen.keys())[0]

        # 初始化队列
        print("Queue is being created...")
        q.put({"type": "screen", "operation": "set_screen", "data": {"screen_id": self.screen_id}})

        # 启动主循环线程
        thread = threading.Thread(target=self.main_loop)
        thread.daemon = False
        thread.start()

    def operation(self, data):
        global PyScreen
        global event_list

        if data["type"] == "screen":
            # 屏幕操作
            if data["operation"] == "set_screen":
                # 开始加载屏幕
                screen_id = data["data"]["screen_id"]
                # 初始化屏幕实体列表
                temp_o.clear()
                for i in self.screen[screen_id]:
                    if i == "source":
                        # 背景图片设置
                        x = 0
                        y = 0
                        Object = self.setImage(w=self.ini["w"], h=self.ini["h"], source=self.screen[screen_id]["source"])
                        temp_o[i] = {"O": Object, "x": x, "y": y}
                    else:
                        o = self.screen[screen_id][i]
                        x = o["x"]
                        y = o["y"]
                        if o["type"] == "img":
                            if o["view"]:
                                Object = self.setImage(w=o["w"], h=o["h"], source=o["source"])
                                temp_o[i] = {"O": Object, "x": x, "y": y}
                        if o["type"] == "text":
                            Object = self.setText(font=o["font"], font_size=o["size"], font_color=o["color"], text=o["text"])
                            temp_o[i] = {"O": Object, "x": x, "y": y}
                    PyScreen.blit(Object, (x, y))
                if not event_list == {}:
                    if screen_id in event_list:
                        for ev_item in event_list[screen_id]:

                            movement = ev_item["movement"]
                            oid = ev_item["O"]
                            if movement == "click":  # 点击事件
                                # 创建一个 mask 对象
                                pygame.mask.from_surface(temp_o[oid]["O"])


            elif data["operation"] == "re_screen":
                PyScreen.fill((self.ini["color"]["r"], self.ini["color"]["g"], self.ini["color"]["b"]))
                for o in temp_o:
                    PyScreen.blit(temp_o[o]["O"], (temp_o[o]["x"], temp_o[o]["y"]))
            elif data["operation"] == "change_text":
                # 获取原有数据
                screen_id = self.screen_id
                if data["data"]["screenId"] == screen_id:
                    x = temp_o[data["data"]["O"]]["x"]
                    y = temp_o[data["data"]["O"]]["y"]
                    o = self.screen[screen_id][data["data"]["O"]]
                    Object = self.setText(font=o["font"], font_size=o["size"], font_color=o["color"], text=data["data"]["text"])
                    temp_o[data["data"]["O"]] = {"O": Object, "x": x, "y": y}
                    PyScreen.blit(Object, (x, y))
            elif data["operation"] == "mouse_click":
                mouse_pos = data["data"]["mouse_pos"]
                if self.screen_id in event_list:
                    event_list_item = event_list[self.screen_id]
                    for ev_item in event_list_item:
                        if ev_item["movement"] == "click":
                            relative_pos = (
                                mouse_pos[0] - temp_o[ev_item["O"]]["O"].get_rect().x,
                                mouse_pos[1] - temp_o[ev_item["O"]]["O"].get_rect().y)
                            print(temp_o[ev_item["O"]]["O"].get_rect().x, temp_o[ev_item["O"]]["O"].get_rect().y, mouse_pos[0], mouse_pos[1])
                            try:
                                if ev_item["mask"].get_at(relative_pos):
                                    ev_item["event"]()
                            except IndexError as e:
                                print("回调出错啦！没有点击到我哦", e)
            elif data["operation"] == "change_styles":
                oid = data["data"]["O"]
                stylesId = data["data"]["styleId"]
                screen_id = data["data"]["screenId"]
                o_x = temp_o[data["data"]["O"]]["x"]
                o_y = temp_o[data["data"]["O"]]["y"]
                o = self.screen[screen_id][oid]
                w = o["w"]
                h = o["h"]
                if stylesId == "0":
                    source = o["source"]
                else:
                    source = o["styles"][stylesId]
                image = pygame.image.load(source)
                image = pygame.transform.scale(image, (w, h))
                temp_o[oid] = {"O": image, "x": o_x, "y": o_y}

                PyScreen.blit(image, (o_x, o_y))

        elif data["type"] == "move":
            # 移动操作
            # 此处x为位移
            oid = data["data"]["O"]
            if data["operation"] == "move":
                direction = data["data"]["direction"]
                x = data["data"]["x"]
                if direction == "l":  # 左移
                    temp_o[oid]["x"] -= x
                    self.screen[self.screen_id][oid]["x"] -= x
                elif direction == "r":  # 右移
                    temp_o[oid]["x"] += x
                    self.screen[self.screen_id][oid]["x"] += x
                elif direction == "u":  # 上移
                    temp_o[oid]["y"] -= x
                    self.screen[self.screen_id][oid]["y"] -= x
                elif direction == "d":  # 下移
                    temp_o[oid]["y"] += x
                    self.screen[self.screen_id][oid]["y"] += x
                PyScreen.blit(temp_o[oid]["O"], (temp_o[oid]["x"], temp_o[oid]["y"]))
        elif data["type"] == "event":
            if data["operation"] == "newEvent":
                movement = data["data"]["movement"]
                oid = data["data"]["oid"]
                screenId = data["data"]["screenId"]
                event = data["data"]["event"]
                if movement == "click":  # 点击事件
                    # 创建一个 mask 对象
                    #print(temp_o,oid)
                    """while oid in temp_o:
                        pass"""
                    mask = pygame.mask.from_surface(temp_o[oid]["O"].convert_alpha())
                    if screenId not in event_list:
                        event_list[screenId] = []
                    event_list[screenId].append({"O": oid, "event": event, "mask": mask, "movement": movement})


    def OMove(self, o, direction, x):
        # 运用队列
        q.put({"type": "move", "operation": "move", "data": {"direction": direction, "x": x, "O": o}})
        self.reScreen()

    def reScreen(self):
        q.put({"type": "screen", "operation": "re_screen"})

    def changeScreen(self, screen_id):
        self.screen_id = screen_id
        q.put({"type": "screen", "operation": "set_screen", "data": {"screen_id": screen_id}})
        self.reScreen()

    def changeText(self, screenId, oid, text):
        q.put({"type": "screen", "operation": "change_text", "data": {"O": oid, "text": text, "screenId": screenId}})
        self.reScreen()

    def eventObject(self, screenId, oid, movement, event):
        q.put({"type": "event", "operation": "newEvent",
               "data": {"oid": oid, "screenId": screenId, "movement": movement, "event": event}})

    def changeStyles(self, screenId, oid, styleId):
        q.put({"type": "screen", "operation": "change_styles",
               "data": {"O": oid, "styleId": styleId, "screenId": screenId}})
        self.reScreen()

    def setText(self, font=None, font_size=36, font_color=None, text=""):
        if font_color is None:
            font_color = {"r": 0, "g": 0, "b": 0}
        if font == "":
            font = None
        font = pygame.font.Font(font, font_size)
        text_color = (font_color["r"], font_color["g"], font_color["b"])  # 黑色
        text_surface = font.render(text, True, text_color)
        return text_surface

    def setImage(self, w, h, source):
        image = pygame.image.load(source)
        image = pygame.transform.scale(image, (w, h))
        Object = image
        return Object
